package com.huage_02.lesson_01;

import com.huage_02.util.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class JDBCTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("用户名:");
        String username = sc.nextLine();
        System.out.println("密码:");
        String password = sc.nextLine();

        boolean flag = login(username,password);
        if(flag){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }

    }

    /**
     * 登录检测
     * @param username 用户名
     * @param password 密码
     * @return boolean
     */
    public static boolean login(String username,String password){
        Connection conn = null;
//        Statement stmt = null;
        PreparedStatement pstmt = null;
        ResultSet re = null;
        try {
            conn = JDBCUtils.getConnection();

//            stmt = conn.createStatement();
            //sql注入问题
//            String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
//            re = stmt.executeQuery(sql);

            String sql = "select * from user where username = ? and password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            re = pstmt.executeQuery();
            return re.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
//            JDBCUtils.closeAll(conn,stmt,re);
            JDBCUtils.closeAll(conn,pstmt,re);
        }
        return false;
    }

}
